"use strict";

var fs = require("fs");
var path = require("path");

var common = requireMod("common");

const logPath = path.resolve(__dirname,"../private/n-log/");
const nginx_pv_tpl = '{ip} - - [{date}] "GET /visit.gif?url={url}&taskId={taskId}&referer={referer}&screen={screen}&fromType={fromType}&dsId={dsId}&timestampId={timestampId}&fromDsId={fromDsId}&fromTimestamp={fromTimestamp}&channelId={channelId}&rnd={rnd} HTTP/1.1" 200 35 "{referer}" "{ua}" "-"';
const nginx_click_tpl = '{ip} - - [{date}] "GET /button.gif?url={url}&taskId={taskId}&dsId={dsId}&timestampId={timestampId}&btnName={btnName}&rnd={rnd} HTTP/1.1" 200 35 "{referer}" "{ua}" "-"';

var config = getSysConfig();
var nLog = requireMod("n-log");
nLog.init(logPath);
nLog.setMaxBlockCount(config.logBuffer);

module.exports = async function (ctx, next) {
    if (ctx.url.indexOf("collect") !== -1) {
        ctx.state.collect.dsId = ctx.state.collect.uuid;
        let data = Object.assign({},ctx.state.collect);
        data.url = encodeURIComponent(data.url);
        let logData = common.labelReplace(
            ctx.state.collect.log_type === "pageview" ? nginx_pv_tpl : nginx_click_tpl
            ,data
        );
        nLog.log(ctx.state.collect.app || "ppp", ctx.state.collect.log_type, logData);
    }

    await next();
}
